package com.example.lenovo.appstore.adapter;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lenovo.appstore.R;
import com.example.lenovo.appstore.activity.WebViewActivity;
import com.example.lenovo.appstore.utils.AppContext;
import com.example.lenovo.appstore.view.MyDialog;
import com.example.lenovo.appstore.view.ShadeImageView;
import com.example.lenovo.interfaca.DialogInterfaca;
import com.example.lenovo.model.CategoryListModel;
import com.jiang.android.pbutton.CProgressButton;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 作者：tb on 2019/3/13.
 * 邮箱：
 * 版本：
 */

public class FlowAdapter extends RecyclerView.Adapter<FlowAdapter.ViewHolder1> {


    private Context context;
    private List<CategoryListModel.CategoryList> data;
    private int code;


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public FlowAdapter(Context context, List<CategoryListModel.CategoryList> data) {
        this.context = context;
        this.data = data;

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public ViewHolder1 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View content;
        content = View.inflate(parent.getContext(), R.layout.item_newcoverflow, new LinearLayout(parent.getContext()));
        return new ViewHolder1(content);
    }

    @Override
    public void onBindViewHolder(@NonNull FlowAdapter.ViewHolder1 holder1, final int position) {

        final ViewHolder1 holder = (ViewHolder1) holder1;
        holder.icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(context, WebViewActivity.class);
                intent1.putExtra("url", "http://i.meituan.com/");
                context.startActivity(intent1);
            }
        });
        holder.install.setText("");
        CProgressButton.initStatusString(new String[]{"下载", "||", "完成", "error", "delete"});
        holder.install.normal(0);
        holder.install.setTextColor(Color.BLACK);
        holder.valueAnimator = ValueAnimator.ofInt(0, 100);
        holder.install.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.isStart) {
                    MyDialog dialog = new MyDialog();
                    dialog.showDialog(context, new DialogInterfaca() {
                        @Override
                        public void finish(boolean isFinished) {
                            if (isFinished) {
//                                    isRunning=true;
                                downLoadAPK("https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk", "QQ", holder);
//                                DownLoadAPKUtil.downLoadAPK(valueAnimator,"QQ","https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk",install,cancelable);
                                holder.isStart = false;
                                Log.e("====", "onFinishi==");
                            }
                        }
                    });
                } else {
                    Log.e("isStarted", "false==");
                    holder.install.normal(1);
//
//                        isRunning=false;
                    holder.valueAnimator.pause();
                    holder.cancelable.cancel();
                    holder.isStart = true;
//
                }
            }
        });
////        holder.name.setText(data.get(position).getName());
////        Glide.with(context).load(URL.baseURL + data.get(position).getImg()).into(holder.icon);
//        holder1.hot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                Intent intent = new Intent(context, SListActivity.class);
////                intent.putExtra("id", data.get(position).getC_id() + "");
////                context.startActivity(intent);
//            }
//        });
//        holder1.hot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(AppContext.getInstance(), AppInfoActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                Log.e("点击====", position + "");
//                context.startActivity(intent);
//            }
//        });
//        switch (getCode()) {
//            case 1:
//                holder1.install.setText("安装");
//                break;
//            case 2:
//                holder1.install.setText("¥10.00");
//                break;
//            case 3:
//                holder1.install.setText("安装");
//                break;
//        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 4)
            return 1;
        return 0;
    }

    class ViewHolder1 extends RecyclerView.ViewHolder {

        private TextView name;
        private com.jiang.android.pbutton.CProgressButton install;
        private ImageView icon;
        private RelativeLayout hot;
        private Callback.Cancelable cancelable;
        private ValueAnimator valueAnimator = null;
        private boolean isFinish = false;
        private boolean isRunning;//是否存在下载任务
        private long download_current;//已下载的大小
        private long down_total;//总大小
        private boolean isStart = true;

        public ViewHolder1(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.title);
            icon = itemView.findViewById(R.id.topimg);
            hot = itemView.findViewById(R.id.gen);
            install = itemView.findViewById(R.id.appaz);
        }
    }

    private void downLoadAPK(String url, String packageName, final ViewHolder1 holder) {
//        执行网络请求操作

//        downLoad.setText("下载中...");
        RequestParams params = new RequestParams(url);
        params.setAutoRename(false);  //设置是否根据头信息命名文件
        params.setAutoResume(true);  //设置文件下载断点续传
        params.setExecutor(new PriorityExecutor(2, true));  //设置加载图片的线程池
        params.setCancelFast(true);  //设置是否可以立即停止
//        设置缓存的路径
        String filePath = AppContext.getInstance().getExternalFilesDir(null) + "/download/" + packageName + ".apk";

//        if(new File(filePath).exists()){
//            //已存在  询问是否删除
//            AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
//            builder.setTitle(getResources().getString(R.string.tishi)).setMessage(getResources().getString(R.string.quedinganzhuang))
//                    .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
////                              执行apk安装的步骤
//                            deleteSingleFile(filePath);
//
////                                deleteSingleFile(file.toString());
////                                Log.e("删除安装包==","删除成功");
//
//                        }
//                    }).setNegativeButton(getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
//            });
//            builder.create().show();
//
//        }else{
//
//        }
        params.setSaveFilePath(filePath);
        holder.cancelable = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(final File file) {
                holder.isStart = true;
//                请求成功时，回调的方法
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle(AppContext.getInstance().getResources().getString(R.string.tishi)).setMessage(AppContext.getInstance().getResources().getString(R.string.quedinganzhuang))
                        .setPositiveButton(AppContext.getInstance().getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                              执行apk安装的步骤
//                                downLoad.setImageResource(R.mipmap.download_apk_);
//                                downLoad.setClickable(true);
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                if (Build.VERSION.SDK_INT >= 24) {//大于7.0
                                    Uri apkUri = FileProvider.getUriForFile(AppContext.getInstance(), "com.example.lenovo.appstore.fileprovider", file);
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                } else {
                                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

                                }
                                context.startActivity(intent);

//                                deleteSingleFile(file.toString());
//                                Log.e("删除安装包==","删除成功");

                            }
                        }).setNegativeButton(AppContext.getInstance().getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        deleteSingleFile(file.toString());
                    }
                });
                builder.create().show();
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                Log.e("onError", throwable.getMessage().toString());
//              请求失败时，会执行的方法
            }

            @Override
            public void onCancelled(CancelledException e) {
                Log.e("onCancelled", e.getMessage().toString());
//              请求被取消时，会执行的方法
//                progressDialog.dismiss();
//                isStart=false;
                holder.install.normal(1);
                holder.valueAnimator.pause();

//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }

            @Override
            public void onFinished() {
//              请求完成时，会执行的方法
                Log.e("onFinished", "onFinished");
                if (holder.isFinish) {
                    holder.install.normal(0);
                } else {
                    holder.install.normal(1);
                }
//                install.normal(2);
//                install.setText("下载");
//                install.
            }

            @Override
            public void onWaiting() {
                Log.e("onWaiting", "onWaiting");
//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }

            @Override
            public void onStarted() {
                Log.e("onStarted", "onStarted");
//                开始网络请求时，会执行的方法
                holder.install.startDownLoad();
                holder.valueAnimator.start();
//                CProgess(0);
            }

            @Override
            public void onLoading(long total, long current, boolean b) {
//                Log.e("total","onLoading=="+total);
//                Log.e("current","onLoading"+current);
//                Log.e("b","onLoading"+b);
                if (total == current) {
                    holder.isFinish = true;
                    holder.isRunning = false;
                } else {
                    holder.isFinish = false;
                    holder.isRunning = true;
                }
                holder.down_total = total;
                holder.download_current = current;
//                  设置对话框当中的进度条
//                progressDialog.setProgress((int)(current*100/total));
                holder.install.download((int) (current * 100 / total));

            }
        });

    }

}

